<!-- 选择材料弹窗 -->
<template>
  <el-dialog
    v-model="dialogFormVisible"
    title="选择材料"
    width="70%"
    draggable
    overflow
    @close="handleClose"
  >
    <div class="crossRope" />
    <el-form style="margin-top: 2%">
      <el-row>
        <el-col :span="6">
          <div class="tree-container">
            <el-tree
              :data="rootNodes"
              :props="defaultProps"
              node-key="id"
              :load="loadNode"
              lazy
              :expand-on-click-node="false"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span @click="handleNodeClick(data)">
                    {{ data.categoryName }}
                  </span>
                  <el-button
                    v-if="data.hasChildren"
                    type="text"
                    size="small"
                    @click.stop="node.expand()"
                  >
                    展开
                  </el-button>
                </span>
              </template>
            </el-tree>
          </div>
        </el-col>
        <el-col :span="18">
          <el-row>
            <el-col :span="8">
              <el-form-item label="材料编码" style="width: 85%">
                <el-input
                  v-model="searchForm.materialCode"
                  size="small"
                  placeholder="请输入 材料编码"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="材料名称" style="width: 85%">
                <el-input
                  v-model="searchForm.materialName"
                  size="small"
                  placeholder="请输入 材料名称"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格" style="width: 85%">
                <el-input
                  v-model="searchForm.materialSpecifications"
                  size="small"
                  placeholder="请输入 规格"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" style="text-align: right">
              <el-button
                size="small"
                color="#1E3485"
                :icon="Search"
                @click="
                  tablePage.currentPage = 1;
                  getList();
                "
                >搜索</el-button
              >
              <el-button size="small" :icon="Delete" @click="clearInput()"
                >清空</el-button
              >
            </el-col>
          </el-row>
          <vxe-table
            ref="xTable"
            border
            min-height="350"
            max-height="550"
            header-align="center"
            :column-config="{ resizable: true }"
            :row-config="{ isHover: true }"
            :data="materialTableData"
            :loading="tableLoading"
            size="mini"
            style="margin-top: 2%"
            :pager-config="tablePage"
            @radio-change="handleRadioChange"
          >
            <vxe-column type="radio" width="60" align="center" />
            <vxe-column
              v-for="column in materialTableColumns"
              :key="column.field"
              :field="column.field"
              :title="column.title"
              :min-width="column.width"
              :align="column.align"
              show-overflow
            >
              <template v-slot:default="{ row }">
                {{ row[column.field] }}
              </template>
            </vxe-column>
          </vxe-table>
          <vxe-pager
            v-model:current-page="tablePage.currentPage"
            v-model:page-size="tablePage.pageSize"
            :layouts="[
              'Sizes',
              'PrevJump',
              'PrevPage',
              'Number',
              'NextPage',
              'NextJump',
              'FullJump',
              'Total'
            ]"
            :total="tablePage.total"
            size="mini"
            style="margin-top: 2%"
            @page-change="handlePageChange"
          />
        </el-col>
      </el-row>
    </el-form>
    <div class="crossRope" style="margin-top: 2%" />
    <div style="text-align: right; margin-top: 2%">
      <el-button
        color="#1E3485"
        :icon="Select"
        size="small"
        @click="selectConfirm"
        >确定</el-button
      >
      <el-button :icon="CloseBold" size="small" @click="handleClose"
        >关闭</el-button
      >
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, reactive } from "vue";
import { ElDialog, ElMessage } from "element-plus";
import { VxePagerEvents } from "vxe-table";
import { Delete, Search, Select, CloseBold } from "@element-plus/icons-vue";
import { getMaterialList } from "@/api/ERP_sales";
import { getMaterialCategoryTree } from "@/api/ERP_public";

// 弹窗关闭/打开事件
const props = defineProps({
  visible: Boolean
});
const dialogFormVisible = ref(false);
watch(
  () => props.visible,
  val => {
    dialogFormVisible.value = val;
  },
  { immediate: true }
);
const emit = defineEmits(["close", "confirm"]);
function handleClose() {
  emit("close", false);
}

// 左侧树形图
const defaultProps = {
  children: "children",
  label: "categoryName"
};
const rootNodes = ref([]);
const loadNode = async (node: any, resolve: Function) => {
  const nodeId = node.data.id;
  const childrenData = await getTreeList(nodeId);
  resolve(childrenData);
};
// 获取数据
async function getTreeList(parentId?: string) {
  let params: ApiParams = {};
  if (parentId) {
    params = { parentId };
  }
  const response: ApiResponse = await getMaterialCategoryTree(params);
  if (response.code === 200) {
    return response.data.map((item: any) => ({
      id: item.id,
      categoryName: item.categoryName,
      parentId: item.parentId,
      hasChildren: item.hasChildren,
      children: []
    }));
  }
  throw new Error(response.msg);
}
// 树形图点击事件
function handleNodeClick(data: any) {
  searchForm.materialCategoryId = data.id;
  getList();
}

// 右侧搜索
let searchForm = reactive({
  materialCategoryId: "", // 左侧树形图ID
  materialCode: "", // 材料编码
  materialName: "", // 材料名称
  materialSpecifications: "" // 规格
});
// 清空按钮
function clearInput() {
  searchForm.materialCode = "";
  searchForm.materialName = "";
  searchForm.materialSpecifications = "";
}
// 表格内容
let materialTableData = ref([]);
let tableLoading = ref(false);
const materialTableColumns = ref([
  {
    field: "materialCode",
    title: "材料编码",
    width: 100,
    align: "center"
  },
  {
    field: "materialName",
    title: "材料名称",
    width: 100,
    align: "center"
  },
  {
    field: "materialSpecifications",
    title: "规格",
    width: 100,
    align: "left"
  },
  {
    field: "materialModel",
    title: "型号",
    width: 60,
    align: "center"
  },
  {
    field: "materialTexture",
    title: "材质",
    width: 60,
    align: "center"
  },
  {
    field: "materialUnit",
    title: "单位",
    width: 60,
    align: "center"
  },
  {
    field: "materialDesc",
    title: "备注",
    width: 60,
    align: "center"
  }
]);
const selectedRow = ref(null as any);
const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
});
const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize
}) => {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  getList();
};
const handleRadioChange = event => {
  selectedRow.value = event.row; // 更新选中行的数据
};
// 获取表格数据
async function getList() {
  tableLoading.value = true;
  let params: ApiParams = {};
  params.pageIndex = tablePage.currentPage;
  params.pageSize = tablePage.pageSize;
  params.materialCategoryId = searchForm.materialCategoryId;
  params.materialCode = searchForm.materialCode;
  params.materialName = searchForm.materialName;
  params.materialSpecifications = searchForm.materialSpecifications;
  try {
    const response: ApiResponse = await getMaterialList(params);
    if (response.code === 200) {
      materialTableData.value = response.data.records;
      tablePage.total = response.data.totalElements;
    }
  } catch (error) {
  } finally {
    tableLoading.value = false;
  }
}

// 确认事件
function selectConfirm() {
  if (selectedRow.value.length === 0) {
    ElMessage.error("请选择一条数据");
  } else {
    emit("confirm", {
      selectedRow: selectedRow.value
    });
    // 关闭弹窗
    handleClose();
  }
}
// 打开弹窗时执行
watch(dialogFormVisible, newValue => {
  if (newValue) {
    getList();
  }
});
</script>

<style lang="scss" scoped>
.tree-container {
  max-height: 450px;
  overflow-y: auto;
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
}
</style>
